package com.emm.yixun.mobile;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.login.LoginActivity;
import com.eroad.product.tools.PopuContent;
import com.eroad.product.tools.Result;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.functions.Consumer;

import static android.Manifest.permission.CALL_PHONE;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_CONTACTS;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_CONTACTS;

/**
 * <p><b>Title：</b> 闪屏页</p>
 * <p><b>Description：</b> 进入程序的第一个界面</p>
 *
 * @author tangxin
 * @date 2016年12月6日 下午3:34:04
 */
public class MainActivity extends BaseActivity {

    private static final String TAG = "MainActivity";

    RelativeLayout bg_ll;

    TextView version_name;
    View startView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        startView = View.inflate(this, R.layout.activity_main_main, null);
        setContentView(startView);
        bg_ll = (RelativeLayout) findViewById(R.id.bg_ll);
        version_name = (TextView) findViewById(R.id.version_name);
        requestPermissions();
        EmmApplication.initJsonData(this); // 获取本地数据(省、市、区)
        Intent intent = new Intent(MainActivity.this, com.emm.yixun.service.MyService.class);
        startService(intent);
    }

    private void animation() {
        AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);
        aa.setDuration(2000);
        startView.setAnimation(aa);

        aa.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                reDirectTo();
            }
        });
    }

    public static final String PREFS_NAME = "MyPrefsFiles";
    public static final String FIRST_RUN = "firsts";
    private boolean first;

    private void reDirectTo() {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        first = settings.getBoolean(FIRST_RUN, true);
        if ("1".equals(EmmApplication.getIsLogin())) {// 已登录
            startActivity(new Intent(MainActivity.this, com.example.xf.MainActivity.class));
            Log.v(TAG, "IsLogin-->" + EmmApplication.getIsLogin() + "<----->Token==>" + EmmApplication.getToken() + "<----->UserId==>"
                    + EmmApplication.getUserId() + "<--MerchantId-->" + EmmApplication.getData(EmmApplication.merchantId));
        } else {// 未登录
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
        }
        finish();
        overridePendingTransition(R.anim.fade, R.anim.hold);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(MainActivity.this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(MainActivity.this);
        BaseActivity.activity = this;
    }

    private String[] list = new String[]{CALL_PHONE, READ_CONTACTS, CAMERA, READ_EXTERNAL_STORAGE, READ_PHONE_STATE,
            RECORD_AUDIO, WRITE_CONTACTS};

    private void requestPermissions(final int i) {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission.requestEach(list[i])
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            if (i < list.length - 1) {
                                requestPermissions(i + 1);
                            } else {
                                version_name.setText(" v" + EmmApplication.getPackageManager(9));
                                animation();
                            }
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            show(permission.name);
                        } else {
                            show(permission.name);
                        }
                    }
                });
    }

    private void requestPermissions() {
        requestPermissions(0);
    }

    private void show(String name) {
        PopuContent.show(MainActivity.this, "您已拒绝app的" + name + "权限申请，导致部分功能无法正常使用，" +
                "请到设置-权限管理打开M2案场管理所需权限再使用。", -1, new Result() {
            @Override
            public void result() {
                finish();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

}
